<template>
  <div class="printPageContainer">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="模板列表" name="first">
        <div class="printPageTable">
          <div class="pageHeader">
            <el-button data-tracker="P62-1" type="primary" @click="addPage"
              >添加模板</el-button
            >
            <el-button data-tracker="P62-2" type="primary" @click="modifyPage"
              >修改</el-button
            >
            <el-button data-tracker="P62-3" type="danger" @click="deletePage"
              >删除</el-button
            >
          </div>
          <div class="pageTable">
            <el-table
              :data="tableData"
              stripe
              style="width: 100%"
              ref="multipleTable"
              @selection-change="handleSelectionChange"
              tooltip-effect="dark"
              :max-height="maxheight"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column
                prop="template_data"
                label="模板名称"
                width="180"
              >
                <template slot-scope="scope">
                  {{ scope.row.template_data.template_name }}
                </template>
              </el-table-column>
              <!-- <el-table-column prop="address" label="模板类型">
              </el-table-column> -->
              <el-table-column prop="customer_name" label="使用客户">
              </el-table-column>
              <el-table-column prop="create_time" label="创建时间">
                <template slot-scope="scope">
                  {{
                    new Date(Number(scope.row.create_time) * 1000)
                      .toLocaleString()
                      .replace(/:\d{1,2}$/, " ")
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="update_time" label="更新时间">
                <template slot-scope="scope">
                  {{
                    scope.row.update_time !== 0
                      ? new Date(Number(scope.row.update_time) * 1000)
                          .toLocaleString()
                          .replace(/:\d{1,2}$/, " ")
                      : ""
                  }}
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    @click="checkPage(scope.row)"
                    type="text"
                    size="small"
                    data-tracker="P62-4"
                    >查看</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane
        label="模板设计"
        name="second"
        v-if="activeName === 'second'"
      >
        <div class="printPageSetting">
          <el-form
            ref="form"
            :model="formData"
            :rules="rules"
            label-width="120px"
            :inline="true"
          >
            <el-form-item label="使用客户">
              <el-select
                placeholder="请搜索"
                style="width: 600px"
                :allow-create="false"
                :filterable="true"
                :remote="true"
                reserve-keyword
                :remote-method="searchCustomerList"
                v-model="formData.customerId"
                @change="selectedCustomer"
                clearable
              >
                <el-option
                  v-for="item in customerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="模板名称">
              <el-input
                type="text"
                v-model="formData.pageName"
                style="width: 600px"
              ></el-input>
            </el-form-item>
            <el-form-item label="纸张大小">
              <el-select
                v-model="formData.pageSize"
                style="width: 400px"
                @change="changePageSize"
              >
                <el-option label="自定义" value="auto"></el-option>
                <el-option label="A4" value="a4"></el-option>
                <el-option label="B5" value="b5"></el-option>
                <el-option label="A3" value="a3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="宽(mm)" required prop="pageWidth">
              <el-input
                type="text"
                v-model="formData.pageWidth"
                style="width: 100px"
              ></el-input>
            </el-form-item>
            <el-form-item label="高(mm)" required prop="pageHeight">
              <el-input
                type="text"
                v-model="formData.pageHeight"
                style="width: 100px"
              ></el-input>
            </el-form-item>
            <el-form-item label="打印方向">
              <el-select v-model="formData.printDirection" style="width: 400px">
                <el-option label="纵向" :value="1"></el-option>
                <el-option label="横向" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="打印所需字段" required>
              <el-select
                style="width: 900px"
                v-model="fieldNames_modify"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in fieldOptions"
                  :key="item.field_name"
                  :label="item.chinese_name"
                  :value="item.chinese_name"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 100%">
              <div style="position: relative; left: 50%">
                <el-button type="primary" @click="openDesignWindow('form')"
                  >打开设计窗口</el-button
                >
                <el-button type="primary" @click="onSubmit">{{
                  isModify ? "保存并修改模板" : "保存新模板"
                }}</el-button>
                <el-button @click="cancelDesign">取消</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
// import { getLodop } from "@/utils/lodop/LodopFuncs";
import {
  reqPrintPageList,
  reqAddPrintPage,
  reqCustomerList,
  reqPrintPageDetail,
  reqModifyPrintPage,
  reqDeletePrintPage,
  reqFieldList,
} from "@/api/print";
export default {
  name: "Printsettings",
  components: {},
  data() {
    return {
      maxheight: "auto",
      activeName: "first",
      LODOP: {},
      printValue: "", //打印的代码
      isModify: false,
      tableData: [],
      pageDetail: {},
      multipleSelection: [], //多选的数据
      selectedId: "",
      rules: {
        pageWidth: [
          { required: true, message: "请输入纸张宽度", trigger: "blur" },
        ],
        pageHeight: [
          { required: true, message: "请输入纸张高度", trigger: "blur" },
        ],
        fieldNames: [
          { required: true, message: "请输入打印所需字段", trigger: "blur" },
        ],
      },
      formData: {
        //打印设置的参数
        customerId: "", //使用模板的客户的id
        customerName: "", //使用模板的客户的名字
        pageName: "", //模板名称
        pageSize: "", //纸张大小
        pageWidth: "", //宽(mm)
        pageHeight: "", //高(mm)
        printDirection: "", //打印方向,1纵向,2横向,都是固定纸张
        fieldNames: [], //详情返回的字段名
      },
      fieldNames_modify: [], //修改之后的字段组合
      fieldOptions: [], //目前整理出来的所有打印可能会用到的字段
      customerList: [], //客户列表,为了匹配客户id的
    };
  },
  async mounted() {
    this.getTableList();
    if (this.fieldOptions.length === 0) {
      let result = await reqFieldList({
        waybill_id: Math.ceil(Math.random() * 100),
      });
      if (result.code === 10000) {
        this.fieldOptions = result.data;
      } else {
        result = await reqFieldList({
          waybill_id: Math.ceil(Math.random() * 100),
        });
        if (result.code === 10000) {
          this.fieldOptions = result.data;
        } else {
          result = await reqFieldList({
            waybill_id: Math.ceil(Math.random() * 100),
          });
          this.fieldOptions = result.data;
        }
      }
    }
  },
  methods: {
    async createPrintPage(name, width, height, orient) {
      let module = await import("@/utils/lodop/LodopFuncs");
      let that = this;
      this.LODOP = module.getLodop();
      LODOP.PRINT_INITA(0, 0, width * 10, height * 10, name); //打印初始化(修改的时候千万不能加)、设定纸张整体偏移量、设定可视编辑区域大小(比SET_PRINT_PAGESIZE优先级高)
      LODOP.SET_PRINT_PAGESIZE(
        orient,
        width * 10,
        height * 10,
        "CreateCustomPage"
      ); //'CreateCustomPage'是按纸张宽高自定义纸张类型,不加这行就是用户自定选择纸张大小和方向
      this.fieldNames_modify.forEach((item) => {
        if (item !== "运单号" && item !== "订单号") {
          // console.log(item);
          LODOP.ADD_PRINT_TEXT(10, 10, 100, 20, item);
        } else {
          // console.log("条码");
          LODOP.ADD_PRINT_BARCODE(10, 10, 100, 20, "128Auto", item);
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 5);
        }
      });
      LODOP.PRINT_DESIGN();
      if (LODOP.CVERSION)
        CLODOP.On_Return = function (TaskID, Value) {
          that.printValue = JSON.stringify(Value);
          // console.log(that.printValue);
        };
      // document.getElementById("S1").value = LODOP.PRINT_DESIGN();//没走这步
    },
    addPage() {
      this.activeName = "second";
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    openDesignWindow(form) {
      let that = this;
      if (this.isModify) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            let module = await import("@/utils/lodop/LodopFuncs");
            this.LODOP = module.getLodop();
            eval(JSON.parse(this.printValue));
            LODOP.SET_PRINT_PAGESIZE(
              this.formData.printDirection,
              this.formData.pageWidth * 10,
              this.formData.pageHeight * 10,
              "CreateCustomPage"
            );
            this.fieldNames_modify.forEach((item1) => {
              if (!this.formData.fieldNames.includes(item1)) {
                if (item1 !== "运单号" && item1 !== "订单号") {
                  LODOP.ADD_PRINT_TEXT(10, 10, 100, 20, item1);
                } else {
                  LODOP.ADD_PRINT_BARCODE(10, 10, 100, 20, "128Auto", item1);
                  LODOP.SET_PRINT_STYLEA(0, "FontSize", 5);
                }
              }
            }); //只能检测到新增的
            // this.formData.fieldNames.forEach((item1, index) => {
            //   if (!this.fieldNames_modify.includes(item1)) {
            //     LODOP.SET_PRINT_STYLEA(index * 1, "PreviewOnly", 2);
            //   }
            // }); //只能检测到删除的
            LODOP.PRINT_DESIGN(); //不加这个就不会弹出设计的框
            if (LODOP.CVERSION)
              CLODOP.On_Return = function (TaskID, Value) {
                that.printValue = JSON.stringify(Value);
              };
          } else {
            return false;
          }
        });
      } else {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.createPrintPage(
              this.formData.pageName,
              this.formData.pageWidth,
              this.formData.pageHeight,
              this.formData.printDirection
            );
          } else {
            return false;
          }
        });
      }
    },
    async onSubmit() {
      //提交新建或修改
      if (this.isModify) {
        let result = await reqModifyPrintPage({
          id: this.selectedId,
          customer_id: !this.formData.customerId
            ? 0
            : this.formData.customerId * 1,
          template_data: {
            customer_name: this.formData.customerName,
            template_name: this.formData.pageName,
            template_size: this.formData.pageSize,
            template_width: this.formData.pageWidth,
            template_height: this.formData.pageHeight,
            template_orient: this.formData.printDirection,
            field_names: this.fieldNames_modify,
            template_design: this.printValue,
          },
        });
        if (result.code === 10000) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.isModify = false;
          this.activeName = "first";
          this.getTableList();
          Object.assign(this.$data.formData, this.$options.data().formData);
          this.fieldNames_modify = [];
          this.printValue = "";
        } else {
          this.$message({
            message: result.message,
            type: "error",
          });
        }
      } else {
        let result = await reqAddPrintPage({
          customer_id: !this.formData.customerId
            ? 0
            : this.formData.customerId * 1,
          template_data: {
            customer_name: this.formData.customerName,
            template_name: this.formData.pageName,
            template_size: this.formData.pageSize,
            template_width: this.formData.pageWidth,
            template_height: this.formData.pageHeight,
            template_orient: this.formData.printDirection,
            field_names: this.fieldNames_modify,
            template_design: this.printValue,
          },
        });
        if (result.code === 10000) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.getTableList();
          this.activeName = "first";
          Object.assign(this.$data.formData, this.$options.data().formData);
          this.fieldNames_modify = [];
          this.printValue = "";
        } else {
          this.$message({
            message: result.message,
            type: "error",
          });
        }
      }
    },
    changePageSize(val) {
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
      if (val === "auto") {
        this.formData.pageWidth = "";
        this.formData.pageHeight = "";
      } else if (val === "a4") {
        this.formData.pageWidth = 210;
        this.formData.pageHeight = 297;
      } else if (val === "b5") {
        this.formData.pageWidth = 176;
        this.formData.pageHeight = 250;
      } else if (val === "a3") {
        this.formData.pageWidth = 297;
        this.formData.pageHeight = 420;
      }
    },
    async getTableList() {
      let result = await reqPrintPageList({});
      this.tableData = result.data.list;
      if (this.tableData.length > 6) {
        //两排操作栏
        this.maxheight = document.documentElement.clientHeight - 265;
      } else {
        this.maxheight = "auto";
      }
    },
    searchCustomerList(query) {
      //模糊搜索客户名
      if (query !== "") {
        setTimeout(async () => {
          let result = await reqCustomerList({
            name: query,
            is_send: "1",
          });
          this.customerList = result.data;
          console.log(this.customerList, "this.customerList");
        }, 0);
      } else {
        this.customerList = [];
      }
    },
    selectedCustomer(val) {
      //选择客户
      this.formData.customerId = val;
      this.formData.customerName = this.customerList.find(
        (item) => item.id === val
      ).name;
      console.log(this.formData.customerId, this.formData.customerName);
    },
    async checkPage(val) {
      let module = await import("@/utils/lodop/LodopFuncs");
      //查看模板
      let result = await reqPrintPageDetail({
        id: val.id,
      });
      this.pageDetail = result.data;
      this.LODOP = module.getLodop();
      eval(JSON.parse(this.pageDetail.template_data.template_design));
      LODOP.PRINT_DESIGN(); //不加这个就不会弹出设计的框
    },
    async modifyPage() {
      //点击修改的函数
      if (this.multipleSelection.length === 1) {
        this.selectedId = this.multipleSelection[0].id;
        let result = await reqPrintPageDetail({
          id: this.selectedId,
        });
        this.searchCustomerList(this.pageDetail.customer_name);
        this.pageDetail = result.data;
        this.formData.pageName = this.pageDetail.template_data.template_name;
        this.formData.pageSize = this.pageDetail.template_data.template_size;
        this.formData.pageWidth = this.pageDetail.template_data.template_width;
        this.formData.pageHeight =
          this.pageDetail.template_data.template_height;
        this.formData.printDirection =
          this.pageDetail.template_data.template_orient;
        this.formData.fieldNames = this.pageDetail.template_data.field_names;
        this.fieldNames_modify = this.pageDetail.template_data.field_names;
        this.printValue = this.pageDetail.template_data.template_design;
        this.formData.customerId =
          this.pageDetail.customer_id === 0 ? "" : this.pageDetail.customer_id;
        this.formData.customerName =
          this.pageDetail.template_data.template_name;
        this.isModify = true;
        this.activeName = "second";
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      } else {
        this.$message({
          message: "只能同时修改一个模板",
          type: "error",
        });
      }
    },
    async deletePage() {
      //删除模板
      let result = await reqDeletePrintPage({
        ids: this.multipleSelection.map((item) => item.id),
      });
      if (result.code === 10000) {
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.getTableList();
      }
    },
    cancelDesign() {
      //取消添加或修改
      this.activeName = "first";
      Object.assign(this.$data.formData, this.$options.data().formData);
      this.fieldNames_modify = [];
      this.printValue = "";
    },
  },
};
</script>

<style scoped lang="less">
.printPageContainer {
  background-color: #fff;
  // padding: 10px 15px;
  .printPageTable {
    padding: 0 10px;
    .pageHeader {
      margin-bottom: 10px;
    }
  }
  .printPageSetting {
    padding: 80px 10px;
  }
}
</style>
